//
//  YTModifyInfoViewController.m
//  YiTuDriverClient
//
//  Created by 石少庸 on 2017/5/17.
//  Copyright © 2017年 Yitu. All rights reserved.
//

#import "YTModifyInfoViewController.h"
#import "YTLanguageChangeViewController.h"
#import "YTCitySeletedViewController.h"
#import "YTSelecteJobViewController.h"
#import "YTUserProfileServices.h"
#import "YTModifyInfoViewModel.h"
#import "YTProfileModel.h"
#import "YTPickerView.h"

@interface YTModifyInfoViewController ()
// 个人资料
@property (weak, nonatomic) IBOutlet UIImageView *avatarImage;
@property (weak, nonatomic) IBOutlet UILabel *userName;
@property (weak, nonatomic) IBOutlet UILabel *sexText;
@property (weak, nonatomic) IBOutlet UILabel *birthdayText;
@property (weak, nonatomic) IBOutlet UILabel *driverTypeText;
@property (weak, nonatomic) IBOutlet UILabel *serviceCityText;
@property (weak, nonatomic) IBOutlet UILabel *serviceLanguageText;
@property (weak, nonatomic) IBOutlet UILabel *liveCityText;
@property (weak, nonatomic) IBOutlet UILabel *liveYearText;
@property (weak, nonatomic) IBOutlet UILabel *educationText;
@property (weak, nonatomic) IBOutlet UILabel *occupationText;
@property (weak, nonatomic) IBOutlet UIButton *touristCerHas;
@property (weak, nonatomic) IBOutlet UIButton *touristCerNone;

@property (strong, nonatomic) YTModifyInfoViewModel *viewModel;
@property (strong, nonatomic) YTProfileModel *model;
@end

@implementation YTModifyInfoViewController

- (void)initialize {
    _viewModel = [[YTModifyInfoViewModel alloc] init];
    _model = [YTUtilityManager manager].userModel;
    // 修改头像
    [[_viewModel.changeAvatarCommand.executionSignals switchToLatest] subscribeCompleted:^{
        [SVProgressHUD showSuccessWithStatus:@"修改成功"];
    }];
    [_viewModel.saveInfoCommand.executing subscribeNext:[self yt_showHudWithTips:@"拼命上传中"]];
    @weakify(self);
    [[_viewModel.saveInfoCommand.executionSignals switchToLatest] subscribeNext:^(NSDictionary *response) {
        @strongify(self);
        if ([response[@"resultCode"] integerValue] == 1000) {
            [SVProgressHUD showSuccessWithStatus:@"保存成功"];
            [self.navigationController popViewControllerAnimated:YES];
        } else {
            [SVProgressHUD showErrorWithStatus:@"保存失败!"];
        }
    }];
    // 加载信息
    [self loadUserInfo];
}

- (void)bindViewModel {
    RAC(_viewModel, avatarImage) = RACObserve(_avatarImage, image);
    RAC(_liveCityText, text) = RACObserve(_viewModel, liveCity);
    RAC(_serviceCityText, text) = RACObserve(_viewModel, serviceCity);
    RAC(_serviceLanguageText, text) = RACObserve(_viewModel, language);
}

- (void)dealloc {}

#pragma mark - 加载用户信息

- (void)loadUserInfo {
    [_avatarImage yy_setImageWithURL:[NSURL URLWithString:_model.userFace]
                         placeholder:[UIImage imageNamed:@"profile_avatar"]
                             options:YYWebImageOptionShowNetworkActivity
                          completion:nil];
    _userName.text = _model.userName;
    _sexText.text = _model.female == 0 ? @"男" : @"女";
    _birthdayText.text = _model.birthday;
    switch (_model.userRoleNew) {
        case 1:
        case 2:
        case 3:
        case 4:
        case 5:
            _driverTypeText.text = @"个人司导";
            break;
        case 6:
            _driverTypeText.text = @"车队";
            break;
        case 7:
            _driverTypeText.text = @"地接社";
            break;
    }
    
    if (_model.guideCard == 0) {
        _touristCerNone.selected = YES;
        _touristCerHas.selected = NO;
    } else {
        _touristCerNone.selected = NO;
        _touristCerHas.selected = YES;
    }
    _liveYearText.text = _model.lifeYear;
    _liveCityText.text = _model.cityName;
    _educationText.text = _model.education;
    _occupationText.text = _model.job;
    
    for (YTProfileServiceCityModel *city in _model.serviceCity) {
        _serviceCityText.text = [_serviceCityText.text stringByAppendingString:[NSString stringWithFormat:@" %@", city.Name]];
    }
}

#pragma mark - IBAction

// 选择有导游证
- (IBAction)touristHasAction:(UIButton *)sender {
    sender.selected = !sender.selected;
    _touristCerNone.selected = NO;
}

// 选择没有导游证
- (IBAction)touristHasNone:(UIButton *)sender {
    sender.selected = !sender.selected;
    _touristCerHas.selected = NO;
}

- (IBAction)saveUserInfoAction:(UIBarButtonItem *)sender {
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    dict[@"serviceCity"] = _viewModel.serviceCityID;
    dict[@"language"] = _viewModel.languageID;
    dict[@"cityId"] = _viewModel.liveCityID;
    dict[@"lifeYear"] = _liveYearText.text;
    dict[@"guideCard"] = _touristCerHas.selected ? @"1" : @"0";
    dict[@"education"] = _educationText.text;
    dict[@"job"] = _occupationText.text;
    [_viewModel.saveInfoCommand execute:dict];
}

#pragma mark - UITableViewDelegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    BOOL isForeign = (indexPath.section == 1 && (indexPath.row == 1 || indexPath.row == 0));
    if (indexPath.section == 0 && indexPath.row == 0) {
        return 90;
    } else if (isForeign && (_model.isChina != 2)) { // 境内司机不显示居住年限和居住城市
        return 0;
    } else {
        return 44;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.section == 0) {
        switch (indexPath.row) {
            case 0:
                [self changeAvatarImage];
                break;
            case 2:
                [self changeSex];
                break;
            case 3:
//                [self changeBirthday]; // 暂时不能修改这个信息
                break;
        }
    }
    
    if (indexPath.section == 1 && indexPath.row == 1) {
        [self selecteData:_viewModel.lifeYearArray completion:^(NSString *selectedString) {
            self.liveYearText.text = selectedString;
        }];
    }
    
    if (indexPath.section == 3 && indexPath.row == 1) {
        [self changeGreduate];
    }
}

#pragma mark - Private

/** 修改头像*/
- (void)changeAvatarImage {
    @weakify(self);
    [self yt_selecteImageCompletion:^(UIImage * _Nullable image) {
        @strongify(self);
        self.avatarImage.image = image;
        [self.viewModel.changeAvatarCommand execute:nil];
    }];
}

/** 修改性别*/
- (void)changeSex {
    @weakify(self);
    [self selecteData:@[@"男", @"女"] completion:^(NSString *selectedString) {
        @strongify(self);
        self.sexText.text = selectedString;
    }];
}

/** 修改出生日期*/
- (void)changeBirthday {
    YTPickerView *picker = [YTPickerView pickerWithType:YTPickerTypeMonthDay];
    picker.birthday = YES;
    picker.completion = ^(NSString *selectedString) {
        self.birthdayText.text = selectedString;
    };
    [picker show];
}

/** 修改学历*/
- (void)changeGreduate {
    @weakify(self);
    [self selecteData:_viewModel.educationArray
           completion:^(NSString *selectedString) {
               @strongify(self);
               self.educationText.text = selectedString;
    }];
}

/**
 数据选择
 
 @param dataArray 待选数据
 @param completion 完成回调
 */
- (void)selecteData:(NSArray<NSString *> *)dataArray
         completion:(void(^)(NSString *selectedString))completion {
    YTPickerView *picker = [YTPickerView pickerWithType:YTPickerTypeDataSource];
    picker.dataArray = dataArray;
    picker.completion = ^(NSString *selectedString) {
        completion(selectedString);
    };
    [picker show];
}

#pragma mark - segue

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    if ([segue.identifier isEqualToString:@"YTLiveCitySeleted"]) {
        YTCitySeletedViewController *city = segue.destinationViewController;
        city.isInland = ([YTUtilityManager manager].userModel.isChina == 1);
        city.isSeleteLive = YES;
        city.seletedCallBack = [RACSubject subject];
        [city.seletedCallBack subscribeNext:^(RACTuple *tuple) {
            [self.viewModel.liveCommand execute:tuple];
        }];
    }
    
    if ([segue.identifier isEqualToString:@"YTServiceCitySeleted"]) {
        YTCitySeletedViewController *city = segue.destinationViewController;
        city.isInland = ([YTUtilityManager manager].userModel.isChina == 1);
        city.seletedCallBack = [RACSubject subject];
        [city.seletedCallBack subscribeNext:^(RACTuple *tuple) {
            [self.viewModel.serviceCommand execute:tuple];
        }];
    }
    
    if ([segue.identifier isEqualToString:@"YTSeletedLanguage"]) {
        YTLanguageChangeViewController *language = segue.destinationViewController;
        language.selectedCallBack = [RACSubject subject];
        [language.selectedCallBack subscribeNext:^(RACTuple *tuple) {
            self.viewModel.languageID = tuple.second;
            self.viewModel.language = tuple.first;
            self.serviceLanguageText.text = tuple.first;
        }];
    }
    
    if ([segue.identifier isEqualToString:@"YTSeletedJob"]) {
        YTSelecteJobViewController *job = segue.destinationViewController;
        job.dataArray = _viewModel.jobArray;
        job.seletedJobCallBack = ^(NSString *job) {
            self.occupationText.text = job;
        };
    }
}

@end
